package area

import (
	"Project/global"
	"Project/model/area/request"
	"Project/model/user"
	"Project/utils"
	"errors"
	"go.uber.org/zap"
	"log"
)

type AreaUserService struct{}

// EditorAreaUserInfo 修改个人信息
func (a *AreaUserService) EditorAreaUserInfo(userID int64, userInfo request.AreaUserInfoRes)(err error)  {
	ur,err := a.GetUserInfoByID(userID)
	if err != nil {
		log.Println("获取用户信息失败",err)
		global.GVA_LOG.Error("获取用户信息失败",zap.Error(err))
		return
	}
	if ur.UserName == userInfo.UserName && ur.Card == userInfo.UserCard && ur.Phone == userInfo.UserPhone {
		return
	}
	if err = global.GVA_DB.Model(&user.UserArea{}).Where("user_id = ?",userID).Updates(map[string]interface{}{"user_name":userInfo.UserName,"phone":userInfo.UserPhone,"card":userInfo.UserCard}).Error;err != nil{
		log.Println("更新用户信息失败",err)
		return
	}
	return
}

// GetUserInfoByID 根据ID获取用户信息
func (a *AreaUserService) GetUserInfoByID(userID int64)(user user.UserArea,err error){
	if err = global.GVA_DB.Select([]string{"user_name","card","phone"}).Find(&user,"user_id = ?",userID).Error;err != nil {
		return
	}
	return
}

// EditorPassword 修改密码
func (a *AreaUserService) EditorPassword(userID int64,pwdInfo request.PasswordInfo)(err error) {
//  校验原始密码
	ar := user.UserArea{}
	if err =  global.GVA_DB.Find(&ar,"user_id = ?",userID).Error;err != nil{
		return
	}
	if !utils.BcryptCheck(pwdInfo.OldPwd,ar.Password){
		return errors.New("原始密码不正确")
	}
	if pwdInfo.OldPwd == pwdInfo.NewPwd{
		return errors.New("新旧密码相同,请重新修改")
	}
	if pwdInfo.NewPwd != pwdInfo.ConfirmPwd {
		return errors.New("两次输入密码不同")
	}
	if err = global.GVA_DB.Model(&user.UserArea{}).Where("user_id = ?",userID).Update("password",utils.BcryptHash(pwdInfo.NewPwd)).Error;err != nil {
		return err
	}
	return nil
}


